/*
Author : Nguyen Van Ty
Email  : ngvanty03@gmail.com
Date   : 12/26/2010 

*/

using System;
using System.Collections.Generic;
using System.Text;
using log4net;
using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Common;
using BusinessObject;
using Utility;
using System.Xml;
namespace DataAccessLayer
{
    /// <summary>
    /// Define PhieuBanHangDaoBase class. This class user for DataAccessLayer, contain 4 function Insert, Update, Search, Delete.
    /// If you want add new function, you must define in PhieuBanHangDao class , not here.
    /// </summary>
    public class PhieuBanHangDaoBase
    {
        private static ILog logger = null;
        #region Constructor
        /// <summary>
        /// Define Constructor.
        /// </summary>
        public PhieuBanHangDaoBase() { }
        static PhieuBanHangDaoBase()
        {
            //Init logger.
            logger = LoggingUtility.GetLogger(typeof(PhieuBanHangDaoBase).FullName);
        }
        #endregion
        /// <summary>
        /// Read data from IDataReader, convert to PhieuBanHang Object.
        /// </summary>
        private static PhieuBanHang GetPhieuBanHangByDataReader(IDataReader reader)
        {
            String methodName = "GetPhieuBanHangByDataReader";
            if (logger.IsDebugEnabled)
            {
                LoggingUtility.logMethodEntry(logger, methodName);
            }
            try
            {
                PhieuBanHang result = new PhieuBanHang();
                //read MaPhieuBanHang field data.

                result.MaPhieuBanHang = ManagerDao.Getint64DataFromDataReader(reader, "MaPhieuBanHang");

                //read NgayBan field data.

                result.NgayBan = ManagerDao.GetdatetimeDataFromDataReader(reader, "NgayBan");

                //read NguoiBan field data.

                result.NguoiBan = ManagerDao.GetstringDataFromDataReader(reader, "NguoiBan");

                //read TongGiaTien field data.

                result.TongGiaTien = ManagerDao.GetdoubleDataFromDataReader(reader, "TongGiaTien");

                //read MaKho field data.

                result.MaKho = ManagerDao.GetintDataFromDataReader(reader, "MaKho");

                //read MaKhachHang field data.

                result.MaKhachHang = ManagerDao.GetintDataFromDataReader(reader, "MaKhachHang");

                //read NguoiLapPhieu field data.

                result.NguoiLapPhieu = ManagerDao.GetstringDataFromDataReader(reader, "NguoiLapPhieu");

                //read NgayLapPhieu field data.

                result.NgayLapPhieu = ManagerDao.GetdatetimeDataFromDataReader(reader, "NgayLapPhieu");

                return result;
            }
            catch (Exception e)
            {
                // write error to log file.
                logger.Error(methodName, e);
                return null;
            }
        }
        /// <summary>
        /// Define function Insert for PhieuBanHang Object.
        /// </summary>
        /// <param name="obj">Object Insert.</param>
        /// <returns>
        ///    True: Successfull.
        ///    False: Process Error.
        ///</returns>
        public static bool Insert(PhieuBanHang obj)
        {
            bool result = false;
            String methodName = "InsertPhieuBanHang";
            if (logger.IsDebugEnabled)
            {
                LoggingUtility.logMethodEntry(logger, methodName);
            }
            DbCommand cmd = ManagerDao.GetStoredProcCommand("spInsertPhieuBanHang");

            //Add value "NgayBan"  paramater.
            ManagerDao.AddInParameter(cmd, "NgayBan", DbType.DateTime,
                ConvertValueObject.CastObjValueToInsertDB(obj.NgayBan));
            //Add value "NguoiBan"  paramater.
            ManagerDao.AddInParameter(cmd, "NguoiBan", DbType.String,
                ConvertValueObject.CastObjValueToInsertDB(obj.NguoiBan));
            //Add value "TongGiaTien"  paramater.
            ManagerDao.AddInParameter(cmd, "TongGiaTien", DbType.Double,
                ConvertValueObject.CastObjValueToInsertDB(obj.TongGiaTien));
            //Add value "MaKho"  paramater.
            ManagerDao.AddInParameter(cmd, "MaKho", DbType.Int32,
                ConvertValueObject.CastObjValueToInsertDB(obj.MaKho));
            //Add value "MaKhachHang"  paramater.
            ManagerDao.AddInParameter(cmd, "MaKhachHang", DbType.Int32,
                ConvertValueObject.CastObjValueToInsertDB(obj.MaKhachHang));
            //Add value "NguoiLapPhieu"  paramater.
            ManagerDao.AddInParameter(cmd, "NguoiLapPhieu", DbType.String,
                ConvertValueObject.CastObjValueToInsertDB(obj.NguoiLapPhieu));
            //Add value "NgayLapPhieu"  paramater.
            ManagerDao.AddInParameter(cmd, "NgayLapPhieu", DbType.DateTime,
                ConvertValueObject.CastObjValueToInsertDB(obj.NgayLapPhieu));
            //add paramater store return value.        
            ManagerDao.AddParameter(cmd, "returnValue", DbType.Int32, ParameterDirection.ReturnValue, string.Empty, DataRowVersion.Default, null);
            try
            {
                ManagerDao.ExecuteNonQuery(cmd);
                Int64 id = Int64.Parse(ManagerDao.GetParameterValue(cmd, "returnValue").ToString());

                if (id > 0)//Successfull.
                {
                    result = true;
                }
                else//Error.
                {
                    result = false;
                }
            }
            catch (Exception e)
            {
                //write error message to log file.
                logger.Error(methodName, e);
                result = false;
            }
            return result;
        }

        /// <summary>
        /// Define function Update for PhieuBanHang Object.
        /// </summary>
        /// <param name="obj">Object Update.</param>
        /// <returns>
        ///    True: Successfull.
        ///    False: Process Error.
        ///</returns>
        public static bool Update(PhieuBanHang obj)
        {
            bool result = false;
            String methodName = "UpdatePhieuBanHang";
            if (logger.IsDebugEnabled)
            {
                LoggingUtility.logMethodEntry(logger, methodName);
            }
            DbCommand cmd = ManagerDao.GetStoredProcCommand("spUpdatePhieuBanHang");


            //Add value "MaPhieuBanHang"  paramater.
            ManagerDao.AddInParameter(cmd, "MaPhieuBanHang", DbType.Int64, ConvertValueObject.CastObjValueToInsertDB(obj.MaPhieuBanHang));
            //Add value "NgayBan"  paramater.
            ManagerDao.AddInParameter(cmd, "NgayBan", DbType.DateTime, ConvertValueObject.CastObjValueToInsertDB(obj.NgayBan));
            //Add value "NguoiBan"  paramater.
            ManagerDao.AddInParameter(cmd, "NguoiBan", DbType.String, ConvertValueObject.CastObjValueToInsertDB(obj.NguoiBan));
            //Add value "TongGiaTien"  paramater.
            ManagerDao.AddInParameter(cmd, "TongGiaTien", DbType.Double, ConvertValueObject.CastObjValueToInsertDB(obj.TongGiaTien));
            //Add value "MaKho"  paramater.
            ManagerDao.AddInParameter(cmd, "MaKho", DbType.Int32, ConvertValueObject.CastObjValueToInsertDB(obj.MaKho));
            //Add value "MaKhachHang"  paramater.
            ManagerDao.AddInParameter(cmd, "MaKhachHang", DbType.Int32, ConvertValueObject.CastObjValueToInsertDB(obj.MaKhachHang));
            //Add value "NguoiLapPhieu"  paramater.
            ManagerDao.AddInParameter(cmd, "NguoiLapPhieu", DbType.String, ConvertValueObject.CastObjValueToInsertDB(obj.NguoiLapPhieu));
            //Add value "NgayLapPhieu"  paramater.
            ManagerDao.AddInParameter(cmd, "NgayLapPhieu", DbType.DateTime, ConvertValueObject.CastObjValueToInsertDB(obj.NgayLapPhieu));
            // add parameter store return value.
            ManagerDao.AddParameter(cmd, "returnValue", DbType.Int32, ParameterDirection.ReturnValue, string.Empty, DataRowVersion.Default, null);
            try
            {
                ManagerDao.ExecuteNonQuery(cmd);
                int rows = (int)ManagerDao.GetParameterValue(cmd, "returnValue");
                if (rows == 1)//Successfull.
                {
                    result = true;
                }
                else//Error.
                {
                    result = false;
                }

            }
            catch (Exception e)
            {
                //write error Message to log file.
                logger.Error(methodName, e);
                result = false;
            }
            return result;
        }
        /// <summary>
        /// Get Data PhieuBanHang object. 
        /// </summary>
        /// <param name="maPhieuBanHang" >This is primary key to get data.</param>
        /// <returns>PhieuBanHang object.</returns>

        public static PhieuBanHang Get(Int64 maPhieuBanHang)
        {
            String methodName = "GetPhieuBanHang";
            if (logger.IsDebugEnabled)
            {
                LoggingUtility.logMethodEntry(logger, methodName);
            }
            try
            {
                PhieuBanHang result = null;
                DbCommand dbCommnand = ManagerDao.GetStoredProcCommand("spGetPhieuBanHang");
                //Add value "MaPhieuBanHang"  paramater.
                ManagerDao.AddInParameter(dbCommnand, "MaPhieuBanHang", DbType.Int64, maPhieuBanHang);
                IDataReader reader = ManagerDao.ExecuteReader(dbCommnand);
                if (reader.Read())
                {
                    result = GetPhieuBanHangByDataReader(reader);

                }
                reader.Close();
                return result;
            }
            catch (System.Exception e)
            {
                //write error message to log file.
                logger.Error("Get", e);
                return null;
            }
        }
        /// <summary>
        /// Get All PhieuBanHang object from table PhieuBanHang.
        /// </summary>
        /// <returns>List PhieuBanHang object.</returns>
        public static List<PhieuBanHangResult> GetAll()
        {
            String methodName = "GetAll";
            if (logger.IsDebugEnabled)
            {
                LoggingUtility.logMethodEntry(logger, methodName);
            }

            try
            {
                List<PhieuBanHangResult> listPhieuBanHang = new List<PhieuBanHangResult>();
                DbCommand dbCommand = ManagerDao.GetStoredProcCommand("spGetAllPhieuBanHang");

                using (IDataReader reader = ManagerDao.ExecuteReader(dbCommand))
                {
                    while (reader.Read())
                    {
                        listPhieuBanHang.Add(GetPhieuBanHangResultByDataReader(reader));
                    }
                    reader.Close();
                }

                return listPhieuBanHang;
            }
            catch (Exception ex)
            {
                //write error message to log file.
                logger.Error(methodName, ex);
                return null;
            }
        }

        /// <summary>
        /// Search PhieuBanHang object in table PhieuBanHang with condition is t object.
        /// </summary>
        /// <param name="t">Condition for Search.</param>       
        /// <param name="totalRow">  total records in this table.</param>
        /// <returns>List PhieuBanHangResult object.</returns>
        public static List<PhieuBanHangResult> SearchPhieuBanHangSomeCondition(PhieuBanHang t)
        {
            String methodName = "SearchPhieuBanHangSomeCondition";
            if (logger.IsDebugEnabled)
            {
                LoggingUtility.logMethodEntry(logger, methodName);
            }

            try
            {
                List<PhieuBanHangResult> listPhieuBanHang = new List<PhieuBanHangResult>();
                DbCommand cmd = ManagerDao.GetStoredProcCommand("spSearchPhieuBanHangByCondition");
                //Add value Condition  paramater.
                ManagerDao.AddInParameter(cmd, "Condition", DbType.String, ConvertValueObject.CastObjValueToInsertDB(t.Condition));

                //Add value PageIndex  paramater.
                ManagerDao.AddInParameter(cmd, "PageIndex", DbType.Int32, t.ObjectPaging.PageIndex);
                //Add value PageSize  paramater.
                ManagerDao.AddInParameter(cmd, "PageSize", DbType.Int32, t.ObjectPaging.PageSize);
                //Add value SortField  paramater.
                ManagerDao.AddInParameter(cmd, "SortField", DbType.String, t.ObjectSortOrder.SortField);
                //Add value SortExpression  paramater.
                ManagerDao.AddInParameter(cmd, "SortExpression", DbType.String, t.ObjectSortOrder.SortExpression);
                using (IDataReader reader = ManagerDao.ExecuteReader(cmd))
                {
                    while (reader.Read())
                    {
                        listPhieuBanHang.Add(GetPhieuBanHangResultByDataReader(reader));
                        if (t.ToltalRow <= 0)
                            t.ToltalRow = ManagerDao.Getint32DataFromDataReader(reader, "TotalRow");
                    }

                    reader.Close();
                }

                return listPhieuBanHang;
            }
            catch (Exception ex)
            {
                //write error message to log file.
                logger.Error(methodName, ex);
                return null;
            }
        }
        /// <summary>
        /// Delete PhieuBanHang object. 
        /// </summary>
        /// <param name="MaPhieuBanHang" >This is primary key to delete.</param>
        /// <returns>True/False.</returns>

        public static bool Delete(Int64 MaPhieuBanHang)
        {
            String methodName = "DeletePhieuBanHang";
            if (logger.IsDebugEnabled)
            {
                LoggingUtility.logMethodEntry(logger, methodName);
            }

            try
            {
                
                ManagerDao.BeginTransaction();
                List<ChiTietPhieuBanHangResult> lstChiTietOld = ChiTietPhieuBanHangDao.GetByMaPhieuBanHang(MaPhieuBanHang);
                //get MaKho Cu
                PhieuBanHang objOldPhieuBanHang = Get(MaPhieuBanHang);
                if (objOldPhieuBanHang == null)
                {
                    ManagerDao.Rollback();
                    return false;
                }               
                try
                {
                    //rollback old data
                    foreach (ChiTietPhieuBanHangResult objOldDetail in lstChiTietOld)
                    {
                        //Update MatHangTonKho
                        MatHangTonKho objTonKho = new MatHangTonKho();
                        objTonKho.MaDonViTinh = objOldDetail.MaDonViTinh;
                        objTonKho.MaKho = objOldPhieuBanHang.MaKho;
                        objTonKho.MaMatHang = objOldDetail.MaMatHang;
                        objTonKho.SoLuongTon = objOldDetail.SoLuong;
                        if (!MatHangTonKhoDao.RollBackMatHangTonKho(objTonKho))
                        {
                            ManagerDao.Rollback();
                            return false;
                        }
                    }
                    //delete old data
                    if (!ChiTietPhieuBanHangDao.DeleteByMaPhieuBan(MaPhieuBanHang))
                    {
                        ManagerDao.Rollback();
                        return false;
                    }
                    DbCommand dbCommand = ManagerDao.GetStoredProcCommand("spDeletePhieuBanHang");
                    //Add value "MaPhieuBanHang"  paramater.
                    ManagerDao.AddInParameter(dbCommand, "MaPhieuBanHang", DbType.Int64, MaPhieuBanHang);
                    //Add value returnValue  paramater.
                    ManagerDao.AddParameter(dbCommand, "returnValue", DbType.Int32, ParameterDirection.ReturnValue, string.Empty, DataRowVersion.Default, null);
                    ManagerDao.ExecuteNonQuery(dbCommand);
                    int parameterValue = (int)ManagerDao.GetParameterValue(dbCommand, "returnValue");
                    if (parameterValue == 1)
                    {
                        ManagerDao.Commit();
                        return true;
                    }
                    else
                    {
                        ManagerDao.Rollback();
                        return true;
                    }
                }
                catch (Exception)
                {
                    
                }
                
            }
            catch (Exception e)
            {
                //write error message to log file.
                logger.Error(methodName, e);
               
            }
            ManagerDao.Rollback();
            return true;
        }
        /// <summary>
        /// Read data from IDataReader, convert to PhieuBanHangResult Object.
        /// </summary>
        private static PhieuBanHangResult GetPhieuBanHangResultByDataReaderByLanguage(IDataReader reader, string LanguageId)
        {
            String methodName = "GetPhieuBanHangResultByDataReader";
            if (logger.IsDebugEnabled)
            {
                LoggingUtility.logMethodEntry(logger, methodName);
            }
            try
            {
                PhieuBanHangResult result = new PhieuBanHangResult();
                //read MaPhieuBanHang field data.
                result.MaPhieuBanHang = ManagerDao.Getint64DataFromDataReader(reader, "MaPhieuBanHang");

                //read NgayBan field data.
                result.NgayBan = ManagerDao.GetdatetimeDataFromDataReader(reader, "NgayBan");

                //read NguoiBan field data.
                result.NguoiBan = ManagerDao.GetstringDataFromDataReader(reader, "NguoiBan");

                //read TongGiaTien field data.
                result.TongGiaTien = ManagerDao.GetdoubleDataFromDataReader(reader, "TongGiaTien");

                //read MaKho field data.
                result.MaKho = ManagerDao.GetintDataFromDataReader(reader, "MaKho");

                //read MaKhachHang field data.
                result.MaKhachHang = ManagerDao.GetintDataFromDataReader(reader, "MaKhachHang");

                //read NguoiLapPhieu field data.
                result.NguoiLapPhieu = ManagerDao.GetstringDataFromDataReader(reader, "NguoiLapPhieu");

                //read NgayLapPhieu field data.
                result.NgayLapPhieu = ManagerDao.GetdatetimeDataFromDataReader(reader, "NgayLapPhieu");

                return result;
            }
            catch (Exception e)
            {
                // write error to log file.
                logger.Error(methodName, e);
                return null;
            }
        }
        /// <summary>
        /// Read data from IDataReader, convert to PhieuBanHangResult Object.
        /// </summary>
        private static PhieuBanHangResult GetPhieuBanHangResultByDataReader(IDataReader reader)
        {
            String methodName = "GetPhieuBanHangResultByDataReader";
            if (logger.IsDebugEnabled)
            {
                LoggingUtility.logMethodEntry(logger, methodName);
            }
            try
            {
                PhieuBanHangResult result = new PhieuBanHangResult();
                //read MaPhieuBanHang field data.
                result.MaPhieuBanHang = ManagerDao.Getint64DataFromDataReader(reader, "MaPhieuBanHang");

                //read NgayBan field data.
                result.NgayBan = ManagerDao.GetdatetimeDataFromDataReader(reader, "NgayBan");

                //read NguoiBan field data.
                result.NguoiBan = ManagerDao.GetstringDataFromDataReader(reader, "NguoiBan");
                result.TenKho = ManagerDao.GetstringDataFromDataReader(reader, "TenKho");

                //read TongGiaTien field data.
                result.TongGiaTien = ManagerDao.GetdoubleDataFromDataReader(reader, "TongGiaTien");

                //read MaKho field data.
                result.MaKho = ManagerDao.GetintDataFromDataReader(reader, "MaKho");

                //read MaKhachHang field data.
                result.MaKhachHang = ManagerDao.GetintDataFromDataReader(reader, "MaKhachHang");

                //read NguoiLapPhieu field data.
                result.NguoiLapPhieu = ManagerDao.GetstringDataFromDataReader(reader, "NguoiLapPhieu");

                //read NgayLapPhieu field data.
                result.NgayLapPhieu = ManagerDao.GetdatetimeDataFromDataReader(reader, "NgayLapPhieu");

                return result;
            }
            catch (Exception e)
            {
                // write error to log file.
                logger.Error(methodName, e);
                return null;
            }
        }

    }
}